<?php
/**  class.pagefactory.php
 * 
 * The page factory is where the main DOM is loaded and additional elements are inserted into the DOM then spat back out as HTML
 * 
 * @author Ted, tass2001-at-gmail-dot-com
 * @package phpsimpleblog
 * @version $Id: class.pagefactory.php 13 2013-03-31 02:20:53Z tass2001@gmail.com $
 * @website https://code.google.com/p/phpsimpleblog/
 *
 */
class PageFactory extends BlogBase{
    //Initiate the main variable DOM statically
    static $html_dom = false;
    static $has_printed = false;
    /*
     * Construct our parent object then initiate our own variables
     */
    public function __construct(){
	parent::__construct();
	if(!self::$html_dom)
	    self::$html_dom = $this->__load_main(DOC_ROOT.$this->config->base_layout);
	$this->html_dom = self::$html_dom;
    }

    /* Create a DOM node from the given HTML and return it.
     * @param  String $html	The HTML we shall import to DOM
     * @return DOMElement	The newly created DOM element
     */
    private function __importDOM($html){
	$temp_dom = new DOMDocument();
	$temp_dom->loadHTML($html);
	preg_match('/<([a-zA-Z]{1,}).*?>/',$html,$match_tags);
	return $this->html_dom->importNode($temp_dom->getElementsByTagName($match_tags[1])->item(0),$deep=true);
    }
    
    /* Load our base layout into memory and then replace our placeholders with legitimate data. Once complete load into DOM and return
     * @return DOMDocument $dom
     */
    private function __load_main($file_location){
	$dom = new DOMDocument();
	$file_data = file_get_contents($file_location);
	foreach((array)$this->config->main_page_variables as $text=>$data)
	    $file_data = str_replace(sprintf('%%%s%%',strtoupper($text)),$data,$file_data);
	libxml_use_internal_errors(true); //< This is because PHP doesn't consider our HTML5 tags legit
	$dom->loadHTML($file_data);
	libxml_clear_errors();
	//Load the sidebar from cache
	$sidebar_data = json_decode(file_get_contents(DOC_ROOT.$this->config->static_content->sidebar));
	$sidebar = $dom->getElementById('recent_posts');
	foreach($sidebar_data as $item){
	    $link = $dom->createElement('a');
	    $link->setAttribute('class','font-medium');
	    $link->setAttribute('href',$item->href);
	    $link->nodeValue = $item->title;
	    $sidebar->appendChild($link);
	}
	return $dom;
    }
    
    /*
     * Append a DOM Element into the main page DOM at the given ID
     * @param DOMElement $dom 	The DOM to be inserted
     * @param String	 $id	The ID of the node we would like to append $dom to.
     * @return bool True
     */
    public function appendNode($dom,$id='entries'){
	return $this->html_dom->getElementById($id)->appendChild($dom);
    }
    
    /* Import DOM from a pre-defined template into the main page DOM
     * @param  String $file	The path to the template you wish to import
     * @param  DOMElement	The DOM with the new inserted elements
     *
     */
    public function importFromTemplate($name,$type,$replace_array=array()){
	$file_data = file_get_contents(sprintf('%s/%s/%s.%s.htm',DOC_ROOT,'content/templates',$type,$name));
	foreach($replace_array as $text=>$data)
	    $file_data = str_replace (sprintf('%%%s%%',strtoupper($text)),$data,$file_data);
	return $this->__importDOM($file_data);
    }
    
    /* Import DOM from a string into the main page DOM
     * @param  String $text 	The text you would like imported into the DOM.
     * @return DOMElement	The DOM with the new inserted elements
     */
    public function importFromText($text){
	return $this->__importDOM($text);
    }
    
    /* Set node value for items in them DOM
     * @param Array $overrides A multidimenssional array containing the element id/tag and value to substitute.
     * 		This will only set the values for the *first* element that matches the given criteria
     * 		For example: array('tag' => array('title' => 'New Title'),'id' => array('container' => 'Stuff');
     * @return bool True
     */
    public function nodeOverride($overrides){
	if(isset($overrides['tag'])){
	    foreach($overrides as $tag => $val){
		$temp_element = $this->html_dom->getElementsByTagName($tag)->item(0);
		if($temp_element)
		    $temp_element->nodeValue = $val;
	    }
	}
	if(isset($overrides['id'])){
	    foreach($overrides as $id => $val){
		$temp_element = $this->html_dom->getElementById($id);
		if($temp_element)
		    $temp_element->nodeValue = $val;
	    }
	}
	return true;
    }
    
    /* Print out our page once we're done setting it up
     * @return String	The entire DOM object in a flat text file
     */
    public function printPage(){
	$user_data = (AUTH) ? unserialize(AUTH) : false;
	if(!self::$has_printed){
	    self::$has_printed = true;
	    $login_node = ($user_data) ? $this->importFromTemplate('logout','layout',$replace_array=array('NAME' => $user_data['name'])) : $this->importFromTemplate('login','layout');
	    $this->appendNode($login_node,'user');
	    return html_entity_decode($this->html_dom->saveHTML());
	}
	return false;
    }
}
?>